"""
邮件发送相关
@auth:刘飞
@time:2022-01-11
"""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr
import logging

logging.getLogger('django')

"""常量，标识缓存类别"""
TYPE_MAIL = 'email_code'  # 邮箱验证码


class Sendmail:
    def __init__(self, email, code):
        self.receivers = [email]  # 接收邮件人
        self.content = code  # 发送内容-验证码
        self.message = MIMEMultipart()  # 创建一个带附件的实例
        # 第三方 SMTP 服务
        self.mail_host = "smtp.163.com"  # 设置服务器
        self.mail_user = "q867940410@163.com"  # 用户名
        self.mail_pass = "VMIXLNNHZMMERLXZ"  # 口令
        self.sender = 'q867940410@163.com'  # 发件人

    def send_mail(self):
        # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        self.message['From'] = formataddr(['杭州徽华科技', self.sender])

        # 邮件主题
        subject = '您好，您的验证码如下，有效期为15分钟。'
        self.message['Subject'] = Header(subject, 'utf-8')

        # 邮件正文内容
        self.message.attach(MIMEText(self.content, 'plain', 'utf-8'))
        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(self.mail_host, 25)  # 25 为 SMTP 端口号
            smtpObj.login(self.mail_user, self.mail_pass)
            smtpObj.sendmail(self.sender, self.receivers, self.message.as_string())
            smtpObj.quit()
            return True
        except smtplib.SMTPException as e:
            logging.error(f'邮件发送报错:{str(e)}')
            return False


if __name__ == '__main__':
    S = Sendmail('867940410@qq.com', '123456')
    S.send_mail()
